package com.snow.framework.core.utils;

import org.apache.commons.beanutils.PropertyUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Comparator;

public class ComparatorBigDecimalUtils<T> implements Comparator<T> {

    //排序方式，true-由小到大排序，false-由大到小排序
    private boolean order = true;

    //排序用到的列
    private String comparedFiled;

    /**
     * @desc 默认由小到大排序
     * @param comparedFiled
     */
    public ComparatorBigDecimalUtils(String comparedFiled){
        this.comparedFiled = comparedFiled;
    }

    /**
     * @desc
     * @param order
     * @param comparedFiled
     */
    public ComparatorBigDecimalUtils(boolean order, String comparedFiled){
        this.order = order;
        this.comparedFiled = comparedFiled;
    }

    @Override
    public int compare(T o1, T o2) {
        if(null!=o1 && null!=o2){
            try {
                BigDecimal object1 = new BigDecimal(PropertyUtils.getProperty(o1, comparedFiled).toString());
                BigDecimal object2 = new BigDecimal(PropertyUtils.getProperty(o2, comparedFiled).toString());
                if(order){
                    return object1.compareTo(object2);
                }else {
                    return object2.compareTo(object1);
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }


    public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal("10.00");

        BigDecimal b2 = new BigDecimal("10.01");


    }
}
